<template>
  <div class="org-page">
    <!-- 返回按鈕 -->
    <BackButton />
    
    <div class="org-info-card" v-if="orgInfo">
      <div class="org-avatar-container">
        <img v-if="isValidImageUrl(orgInfo.avatarUrl)" :src="getOrgAvatarUrl(orgInfo.avatarUrl)" class="org-avatar" @error="handleOrgAvatarError" />
        <div v-else class="org-avatar-placeholder">企业头像</div>
        <!-- 换头像按钮 - 仅高管可见 -->
        <view v-if="canChangeOrgAvatar" class="org-avatar-change-btn" @click="uploadOrgAvatar">
          <text class="change-icon">更换</text>
        </view>
      </div>
      <h2>{{ orgInfo.name }}</h2>
      <div class="org-detail">
        <div>统一社会信用代码：{{ orgInfo.creditCode }}</div>
        <div>联系人：{{ orgInfo.contactName || '未填写' }}</div>
        <div>联系电话：{{ orgInfo.contactPhone || '未填写' }}</div>
        <div>企业口号：{{ orgInfo.slogan || '未填写' }}</div>
        <div>地址：{{ orgInfo.address || '未填写' }}</div>
        <div>成立时间：{{ orgInfo.establishedDate || '未填写' }}</div>
      </div>
    </div>

    <div class="org-actions" v-if="orgInfo">
      <button v-if="!userCreditCode" @click="applyJoin" class="org-btn">申请加入</button>
      <template v-else-if="userCreditCode === orgInfo.creditCode">
        <div class="org-member-info">
          <span>你已是该企业成员</span>
          <span v-if="isExecutive" class="org-admin-tag">（你是企业管理员）</span>
        </div>
        <div class="org-buttons">
          <button @click="showMembers = !showMembers" class="org-btn">查看企业成员列表</button>
          <button v-if="isExecutive" @click="editOrgInfo" class="org-btn edit-btn">编辑企业信息</button>
        </div>
      </template>
    </div>

    <div v-if="showMembers && members.length" class="org-members-list">
      <h3>企业成员列表</h3>
      <table>
        <thead>
          <tr>
            <th>头像</th>
            <th>昵称</th>
            <th>姓名</th>
            <th>邮箱</th>
            <th>手机号</th>
            <th>高管</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="m in members" :key="m.uid">
            <td>
              <img v-if="isValidImageUrl(m.avatarUrl)" :src="getAvatarUrl(m.avatarUrl)" class="member-avatar" @error="handleMemberAvatarError" />
              <div v-else class="member-avatar-placeholder">{{ m.nickname?.charAt(0) || '?' }}</div>
            </td>
            <td>{{ m.nickname }}</td>
            <td>{{ m.name }}</td>
            <td>{{ m.email }}</td>
            <td>{{ m.phone }}</td>
            <td>
              <span v-if="m.executive === 2" class="legal-badge">法人</span>
              <span v-else-if="m.executive === 1" class="admin-badge">高管</span>
              <span v-else>成员</span>
              <!-- 调试信息 -->
              <div style="font-size: 10px; color: #999; margin-top: 4px;">
                调试: UID={{ m.uid }}, 级别={{ m.executive }}, 可管理={{ canManageMember(m) }}
                <br>当前用户: {{ userStore.profile?.uid }}, 级别: {{ userStore.profile?.executive }}
              </div>
              <div v-if="canManageMember(m)" class="member-actions">
                <!-- 调试信息 -->
                <div style="font-size: 10px; color: #999; margin-bottom: 4px;">
                  调试: 用户级别{{ userStore.profile?.executive }}, 成员级别{{ m.executive }}, 可管理: {{ canManageMember(m) }}
                </div>
                <button
                  v-if="canSetExecutive(m) && m.executive === 0"
                  class="set-executive-btn"
                  @click="setExecutive(m.uid, m.nickname, 1)"
                >设为高管</button>
                <button
                  v-if="canSetExecutive(m) && m.executive === 1"
                  class="remove-executive-btn"
                  @click="setExecutive(m.uid, m.nickname, 0)"
                >取消高管</button>
                <button
                  v-if="m.executive !== 2"
                  class="kick-btn"
                  @click="kickMember(m.uid, m.nickname)"
                >踢出</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 企业信息编辑模态框 -->
    <div v-if="showEditModal" class="edit-modal-overlay" @click="closeEditModal">
      <div class="edit-modal-content" @click.stop>
        <div class="edit-modal-header">
          <h3>编辑企业信息</h3>
          <button @click="closeEditModal" class="close-btn">×</button>
        </div>
        <div class="edit-modal-body">
          <div class="form-group">
            <label>联系人：</label>
            <input v-model="editForm.contactName" type="text" placeholder="请输入联系人姓名" />
          </div>
          <div class="form-group">
            <label>联系电话：</label>
            <input v-model="editForm.contactPhone" type="text" placeholder="请输入联系电话" />
          </div>
          <div class="form-group">
            <label>企业口号：</label>
            <textarea v-model="editForm.slogan" placeholder="请输入企业口号" rows="3"></textarea>
          </div>
          <div class="form-group">
            <label>企业头像：</label>
            <input v-model="editForm.avatarUrl" type="text" placeholder="请输入头像URL" />
          </div>
          <div class="form-group">
            <label>企业地址：</label>
            <textarea v-model="editForm.address" placeholder="请输入企业地址" rows="2"></textarea>
          </div>
        </div>
        <div class="edit-modal-footer">
          <button @click="closeEditModal" class="cancel-btn">取消</button>
          <button @click="saveOrgInfo" class="save-btn">保存</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { NETWORK_CONFIG } from '@/config/network.js'
import { ref, onMounted, computed, watch } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

import { useUserStore } from '@/store/user'
import BackButton from '@/components/BackButton.vue'
import { getOrgAvatarUrl, getAvatarUrl, isValidImageUrl } from '@/utils/imageUtils.js'

const userStore = useUserStore()
const orgId = ref('')

// 处理企业头像加载错误
const handleOrgAvatarError = () => {
  console.log('企业头像加载失败，使用默认头像');
};

// 处理成员头像加载错误
const handleMemberAvatarError = () => {
  console.log('成员头像加载失败，使用默认头像');
};

// 上传企业头像
const uploadOrgAvatar = async () => {
  try {
    // 选择图片
    const res = await uni.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera']
    });
    
    const tempFilePath = res.tempFilePaths[0];
    const token = uni.getStorageSync('accessToken');
    
    // 上传文件
    const uploadRes = await uni.uploadFile({
      url: `${NETWORK_CONFIG.API_BASE_URL}/organizations/upload-avatar`,
      filePath: tempFilePath,
      name: 'file',
      formData: {
        creditCode: orgInfo.value.creditCode
      },
      header: {
        'Access-Token': `Bearer ${token}`
      }
    });
    
    const data = JSON.parse(uploadRes.data);
    if (data.success) {
      // 更新企业头像URL
      orgInfo.value.avatarUrl = data.filePath;
      
      uni.showToast({
        title: '企业头像上传成功',
        icon: 'success'
      });
    } else {
      throw new Error(data.message || '上传失败');
    }
  } catch (error) {
    console.error('上传企业头像失败:', error);
    uni.showToast({
      title: '上传失败: ' + error.message,
      icon: 'none'
    });
  }
};

// 在onLoad中获取页面参数
onLoad((options) => {
  console.log('企业页面参数:', options)
  if (options && options.id) {
    orgId.value = options.id
    console.log('设置orgId为:', orgId.value)
  }
})

const orgInfo = ref(null)
const members = ref([])
const showMembers = ref(false)
const showEditModal = ref(false)

const userCreditCode = computed(() => {
  console.log('🔍 用户企业代码:', userStore.profile?.creditCode)
  return userStore.profile?.creditCode
})
const isExecutive = computed(() => {
  const executive = userStore.profile?.executive || 0
  console.log('🔍 用户权限级别:', executive)
  return executive >= 1
})

// 检查是否可以更换企业头像（高管或法人）
const canChangeOrgAvatar = computed(() => {
  const executive = userStore.profile?.executive || 0
  const isSameOrg = userStore.profile?.creditCode === orgInfo.value?.creditCode
  return isSameOrg && executive >= 1
})

// 权限检查函数
const canManageMember = (member) => {
  const currentUserLevel = userStore.profile?.executive || 0
  const memberLevel = member.executive || 0  // 后端返回的是executive字段(0/1/2)
  
  console.log('🔍 权限检查详情:')
  console.log('  - 当前用户UID:', userStore.profile?.uid)
  console.log('  - 当前用户级别:', currentUserLevel)
  console.log('  - 目标成员UID:', member.uid)
  console.log('  - 目标成员级别:', memberLevel)
  console.log('  - 目标成员executive:', member.executive)
  console.log('  - 是否为自己:', member.uid === userStore.profile?.uid)
  console.log('  - userStore.profile完整信息:', userStore.profile)
  
  // 不能管理自己
  if (member.uid === userStore.profile?.uid) {
    console.log('  - 结果: 不能管理自己')
    return false
  }
  
  // 法人(isExecutive=2)可以管理所有人
  if (currentUserLevel === 2) {
    console.log('  - 结果: 法人可以管理所有人')
    return true
  }
  
  // 高管(isExecutive=1)只能管理普通成员(isExecutive=0)
  if (currentUserLevel === 1 && memberLevel === 0) {
    console.log('  - 结果: 高管可以管理普通成员')
    return true
  }
  
  console.log('  - 结果: 无权限管理')
  return false
}

const canSetExecutive = (member) => {
  const currentUserLevel = userStore.profile?.executive || 0
  const memberLevel = member.executive || 0  // 后端返回的是executive字段(0/1/2)
  
  // 不能管理自己
  if (member.uid === userStore.profile?.uid) {
    return false
  }
  
  // 只有法人(isExecutive=2)可以设置高管权限
  if (currentUserLevel === 2) {
    return true
  }
  
  return false
}

// 编辑表单数据
const editForm = ref({
  contactName: '',
  contactPhone: '',
  slogan: '',
  avatarUrl: '',
  address: ''
})

onMounted(async () => {
  await fetchOrgInfo()
})

async function fetchOrgInfo() {
  const token = uni.getStorageSync('accessToken')
  console.log('🔍 获取企业信息 - orgId:', orgId.value)
  try {
    const url = `${NETWORK_CONFIG.API_BASE_URL}/organizations/info?creditCode=${encodeURIComponent(orgId.value)}`
    console.log('🔍 请求URL:', url)
    const res = await uni.request({
      url: url,
      method: 'GET',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    console.log('🔍 企业信息响应:', res.data)
    orgInfo.value = res.data
  } catch (err) {
    console.error('获取企业信息失败:', err)
    uni.showToast({
      title: '获取企业信息失败',
      icon: 'none'
    })
  }
}

async function applyJoin() {
  const token = uni.getStorageSync('accessToken')
  try {
    const res2 = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/organizations/apply`,
      method: 'POST',
      data: { creditCode: orgId.value },
      header: { 'Access-Token': `Bearer ${token}` }
    })
    uni.showToast({
      title: '申请已发送，请等待企业高管审核',
      icon: 'success'
    })
  } catch (err2) {
    console.error('申请加入失败:', err2)
    uni.showToast({
      title: '申请失败',
      icon: 'none'
    })
  }
}

async function fetchMembers() {
  const token = uni.getStorageSync('accessToken')
  try {
    const res3 = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/organizations/members?creditCode=${encodeURIComponent(orgId.value)}`,
      method: 'GET',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    console.log('🔍 成员列表响应:', res3.data)
    members.value = res3.data.content || []
    console.log('🔍 处理后的成员列表:', members.value)
  } catch (err3) {
    console.error('获取成员列表失败:', err3)
    uni.showToast({
      title: '获取成员列表失败',
      icon: 'none'
    })
  }
}

watch(showMembers, async (val) => {
  if (val && members.value.length === 0) {
    await fetchMembers()
  }
})

async function kickMember(memberId, nickname) {
  const result = await new Promise((resolve) => {
    uni.showModal({
      title: '确认移除',
      content: `确定要将【${nickname}】移出企业吗？`,
      success: (res) => resolve(res.confirm),
      fail: () => resolve(false)
    })
  })
  
  if (!result) return;
  
  const token = uni.getStorageSync('accessToken');
  try {
    const res4 = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/organizations/kickmember?creditCode=${encodeURIComponent(orgId.value)}&memberId=${memberId}`,
      method: 'DELETE',
      header: { 'Access-Token': `Bearer ${token}` }
    })
    uni.showToast({
      title: '已移除成员',
      icon: 'success'
    })
    await fetchMembers();
  } catch (err4) {
    console.error('移除成员失败:', err4)
    uni.showToast({
      title: '移除成员失败',
      icon: 'none'
    })
  }
}

// 编辑企业信息
function editOrgInfo() {
  // 填充当前企业信息到编辑表单
  editForm.value = {
    contactName: orgInfo.value.contactName || '',
    contactPhone: orgInfo.value.contactPhone || '',
    slogan: orgInfo.value.slogan || '',
    avatarUrl: orgInfo.value.avatarUrl || '',
    address: orgInfo.value.address || ''
  }
  showEditModal.value = true
}

// 关闭编辑模态框
function closeEditModal() {
  showEditModal.value = false
}

// 保存企业信息
async function saveOrgInfo() {
  try {
    const token = uni.getStorageSync('accessToken')
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/organizations/edit`,
      method: 'PUT',
      data: { creditCode: orgId.value, ...editForm.value },
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    uni.showToast({
      title: '企业信息更新成功',
      icon: 'success'
    })
    
    // 刷新企业信息
    await fetchOrgInfo()
    closeEditModal()
  } catch (error) {
    uni.showToast({
      title: '更新失败',
      icon: 'none'
    })
    console.error('更新企业信息失败:', error)
  }
}

// 设置/取消高管权限
async function setExecutive(memberId, nickname, executive) {
  const action = executive === 1 ? '设为高管' : executive === 2 ? '设为法人' : '取消权限'
  
  const result = await new Promise((resolve) => {
    uni.showModal({
      title: '确认操作',
      content: `确定要将【${nickname}】${action}吗？`,
      success: (res) => resolve(res.confirm),
      fail: () => resolve(false)
    })
  })
  
  if (!result) return;
  
  try {
    const token = uni.getStorageSync('accessToken')
    const res = await uni.request({
      url: `${NETWORK_CONFIG.API_BASE_URL}/organizations/executives`,
      method: 'POST',
      data: { 
        creditCode: orgId.value, 
        memberId, 
        executive 
      },
      header: { 'Access-Token': `Bearer ${token}` }
    })
    
    uni.showToast({
      title: `${action}成功`,
      icon: 'success'
    })
    
    // 刷新成员列表
    await fetchMembers()
  } catch (error) {
    uni.showToast({
      title: `${action}失败`,
      icon: 'none'
    })
    console.error(`${action}失败:`, error)
  }
}
</script>

<style scoped>
.org-page {
  max-width: 900px;
  margin: 40px auto;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(0,0,0,0.08);
  padding: 32px;
}
.org-info-card {
  text-align: center;
  margin-bottom: 24px;
}
.org-avatar-container {
  position: relative;
  display: inline-block;
}

.org-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  margin-bottom: 12px;
}

.org-avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 12px;
  color: #999;
  margin-bottom: 12px;
  border: 2px dashed #ccc;
}

.org-avatar-change-btn {
  position: absolute;
  bottom: 0;
  right: 0;
  width: 28px;
  height: 28px;
  background: #007AFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 122, 255, 0.3);
  transition: all 0.2s ease;
  border: 2px solid white;
}

.org-avatar-change-btn:hover {
  background: #0056CC;
  transform: scale(1.1);
}

.change-icon {
  font-size: 10px;
  color: white;
  font-weight: 500;
}
.org-detail {
  margin-top: 12px;
  color: #555;
  font-size: 15px;
  line-height: 2;
}
.org-actions {
  text-align: center;
  margin-bottom: 24px;
}
.org-btn {
  background: linear-gradient(90deg, #6c5ce7, #00b894);
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 10px 32px;
  font-size: 16px;
  margin: 0 8px;
  cursor: pointer;
  transition: background 0.2s;
}
.org-btn:hover {
  background: linear-gradient(90deg, #00b894, #6c5ce7);
}
.org-member-info {
  margin-bottom: 8px;
  font-size: 16px;
  color: #00b894;
}
.org-admin-tag {
  color: #fd79a8;
  margin-left: 8px;
  font-weight: bold;
}
.org-members-list {
  margin-top: 32px;
}
.member-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
}

.member-avatar-placeholder {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #f0f0f0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: #999;
  border: 1px solid #ddd;
}
.admin-badge {
  color: #fff;
  background: #00b894;
  border-radius: 6px;
  padding: 2px 8px;
  font-size: 13px;
}

.legal-badge {
  color: #fff;
  background: #e17055;
  border-radius: 6px;
  padding: 2px 8px;
  font-size: 13px;
}
.kick-btn {
  margin-left: 8px;
  background: linear-gradient(90deg, #ff7675, #fd79a8);
  color: #fff;
  border: none;
  border-radius: 6px;
  padding: 2px 10px;
  font-size: 13px;
  cursor: pointer;
  transition: background 0.2s;
}
.kick-btn:hover {
  background: linear-gradient(90deg, #d63031, #e17055);
}
table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 12px;
}
th, td {
  border-bottom: 1px solid #eee;
  padding: 8px 12px;
  text-align: center;
}

/* 编辑模态框样式 */
.edit-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.edit-modal-content {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
}

.edit-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #eee;
}

.edit-modal-header h3 {
  margin: 0;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
}

.edit-modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
  color: #333;
}

.form-group input,
.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group textarea {
  resize: vertical;
  min-height: 60px;
}

.edit-modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #eee;
}

.cancel-btn {
  background: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  cursor: pointer;
}

.save-btn {
  background: linear-gradient(90deg, #6c5ce7, #00b894);
  color: white;
  border: none;
  border-radius: 6px;
  padding: 10px 20px;
  cursor: pointer;
}

.org-buttons {
  display: flex;
  gap: 12px;
  justify-content: center;
  flex-wrap: wrap;
}

.edit-btn {
  background: linear-gradient(90deg, #fd79a8, #fdcb6e);
}

.member-actions {
  display: flex;
  gap: 6px;
  flex-wrap: wrap;
  justify-content: center;
}

.set-executive-btn {
  background: linear-gradient(90deg, #00b894, #00cec9);
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
}

.remove-executive-btn {
  background: linear-gradient(90deg, #fdcb6e, #e17055);
  color: white;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  font-size: 12px;
  cursor: pointer;
}
</style>
